package util

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/snxamdf/wui/logs"
)

func ToJson(data interface{}) ([]byte, error) {
	if data == nil {
		return nil, errors.New("错误,data 是空")
	}
	switch data.(type) {
	case string:
		return []byte(data.(string)), nil
	}
	if r, err := json.Marshal(data); err != nil {
		logs.Error("对象转JSON错误", err)
		return nil, err
	} else {
		return r, nil
	}
}

func ToObject(data []byte, i interface{}) error {
	if data == nil || i == nil {
		return nil
	}
	if err := json.Unmarshal(data, i); err != nil {
		logs.Error("Json To Object Error", err)
		return err
	}
	return nil
}

func ToArrayJson(dataAray interface{}) {
}

func EventResult(code, etype, widgetId string, data interface{}) (string, error) {
	var jsn, err = ToJson(data)
	return fmt.Sprintf(`{"code":"%s","type":"%s","widgetId":"%s","data":"%s"}`, code, etype, widgetId, jsn), err
}
